package com.tai.network;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/**
 * The type Udp demo.
 *
 * @Desc : UDP测试
 * @Author ： taylor
 * @Date ：2021/6/24 21:56
 */
public class UDPDemo {

    /**
     * UDP发送端
     */
    @Test
    public void send(){

        try (DatagramSocket socket = new DatagramSocket()) {

            String s = "UDP方式发送消息";
            byte[] buffer = s.getBytes();
            InetAddress localHost = InetAddress.getLocalHost();
            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length,localHost,9090);
            socket.send(packet);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * UPDj接收端
     */
    @Test
    public void receiver(){

        try (DatagramSocket socket = new DatagramSocket(9090)) {
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            socket.receive(packet);
            System.out.println(new String(packet.getData(),0,packet.getLength()));
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
